package com.shuorikeji.huohuo.ui.me;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.material.imageview.ShapeableImageView;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.adapter.WtFkTypeAdapter;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.WtFkTypeBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.utils.AndroidBug5497Workaround;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.GlideLoadEngine;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.shuorikeji.huohuo.view.GridDividerItemDecoration;
import com.luck.picture.lib.permissions.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class FkWtActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.siv_fk_photo)
    ShapeableImageView sivFkPhoto;
    @BindView(R.id.iv_add_photo)
    ImageView ivAddPhoto;
    @BindView(R.id.rv_fk_type)
    RecyclerView rvFkType;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_tj_fk)
    TextView tvTjFk;

    private WtFkTypeAdapter wtFkTypeAdapter;
    private List<WtFkTypeBean> typeList = new ArrayList<>();
    private List<String> imgLocalList = new ArrayList<>();
    private List<String> imgNetList = new ArrayList<>();
    private String imgNetUrl = "";
    private String fkTypeStr = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
        AndroidBug5497Workaround.assistActivity(FkWtActivity.this);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_fk_wt);
    }

    @Override
    protected void initData() {
        initAdapter();
        setWtType();
        initClick();
    }

    private void initAdapter() {
        FlexboxLayoutManager manager = new FlexboxLayoutManager(this);
        manager.setFlexDirection(FlexDirection.ROW);
        manager.setFlexWrap(FlexWrap.WRAP);
        rvFkType.addItemDecoration(new GridDividerItemDecoration(20));
        rvFkType.setLayoutManager(manager);
        wtFkTypeAdapter = new WtFkTypeAdapter(FkWtActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        WtFkTypeBean data = (WtFkTypeBean) object;
                        for (int i = 0; i < typeList.size(); i++) {
                            if (data.getContent().equals(typeList.get(i).getContent())) {
                                if (typeList.get(i).isSec()) {
                                    typeList.get(i).setSec(false);
                                } else {
                                    typeList.get(i).setSec(true);
                                }
                                break;
                            }
                        }
                        for (int i = 0; i < typeList.size(); i++) {
                            if (typeList.get(i).isSec()) {
                                fkTypeStr = fkTypeStr + "," + typeList.get(i).getContent();
                            }
                        }
                        fkTypeStr = BusinessUtils.getAllIds(fkTypeStr);
                        wtFkTypeAdapter.setData(typeList);
                        break;
                }
            }
        });
        rvFkType.setAdapter(wtFkTypeAdapter);
    }

    private void setWtType() {
        typeList.clear();

        WtFkTypeBean data = new WtFkTypeBean();
        data.setContent("功能建议");
        data.setSec(false);
        typeList.add(data);
        data = null;

        WtFkTypeBean data1 = new WtFkTypeBean();
        data1.setContent("系统卡顿");
        data1.setSec(false);
        typeList.add(data1);
        data1 = null;

        WtFkTypeBean data2 = new WtFkTypeBean();
        data2.setContent("更新缓慢");
        data2.setSec(false);
        typeList.add(data2);
        data2 = null;

        WtFkTypeBean data3 = new WtFkTypeBean();
        data3.setContent("加载缓慢");
        data3.setSec(false);
        typeList.add(data3);
        data3 = null;

        WtFkTypeBean data4 = new WtFkTypeBean();
        data4.setContent("其他");
        data4.setSec(false);
        typeList.add(data4);
        data4 = null;

        wtFkTypeAdapter.setData(typeList);
    }

    private void rqTxQx(int code) {
        final String[] permissionsGroup = new String[]{
                Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE};
        new RxPermissions(this)
                .request(permissionsGroup)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Log.i("wxl", "上传头像权限申请状态：" + aBoolean);
                        if (aBoolean) {
                            secTxPhoto(code);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void secTxPhoto(int qxCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .capture(true)  // 使用相机，和 captureStrategy 一起使用
                .captureStrategy(new CaptureStrategy(true, "com.ld.music.fileprovider"))
                .theme(R.style.Matisse_Dracula)
                .countable(true)
                .maxSelectable(1)
                .addFilter(new Filter() {
                    @Override
                    protected Set<MimeType> constraintTypes() {
                        return new HashSet<MimeType>() {{
                            add(MimeType.PNG);
                        }};
                    }

                    @Override
                    public IncapableCause filter(Context context, Item item) {
                        try {
                            InputStream inputStream = getContentResolver().openInputStream(item.getContentUri());
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeStream(inputStream, null, options);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.87f)
                .imageEngine(new GlideLoadEngine())
                .forResult(qxCode);
    }

    private void scPhoto() {
        BusinessUtils.upLoadPhotos(imgLocalList, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        imgNetList.clear();
                        imgNetList = (List<String>) object;
                        imgNetUrl = imgNetList.get(0);
                        sivFkPhoto.setVisibility(View.VISIBLE);
                        BusinessUtils.setLoadImg(FkWtActivity.this, imgNetUrl, sivFkPhoto);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(FkWtActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void tjFk() {
        mPresenter.userYjfk(true, etContent.getText().toString(), fkTypeStr, 1, imgNetUrl,
                etPhone.getText().toString(), new ClickCallBack() {
                    @Override
                    public void onClick(int flag, Object object) {
                        switch (flag) {
                            case 1:
                                ToastShowUtil.showToastCenter(FkWtActivity.this, "已提交");
                                finish();
                                break;
                            case 2:
                                String msg = (String) object;
                                ToastShowUtil.showToastCenter(FkWtActivity.this, msg);
                                break;
                        }
                    }
                });
    }

    private void initClick() {
        ivBack.setOnClickListener(view -> {
            finish();
        });
        ivAddPhoto.setOnClickListener(view -> {
            rqTxQx(1001);
        });
        tvTjFk.setOnClickListener(view -> {
            if (BusinessUtils.isEmpty(etContent.getText().toString())) {
                ToastShowUtil.showToastCenter(FkWtActivity.this, "请输入您想反馈问题或意见");
            } else if (BusinessUtils.isEmpty(fkTypeStr)) {
                ToastShowUtil.showToastCenter(FkWtActivity.this, "请选择反馈类型");
            } else if (BusinessUtils.isEmpty(etPhone.getText().toString())) {
                ToastShowUtil.showToastCenter(FkWtActivity.this, "请输入联系方式");
            } else {
                tjFk();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<String> pathList = Matisse.obtainPathResult(data);
            switch (requestCode) {
                case 1001:
                    for (String pathTemp : pathList) {
                        Log.i("wxl", "上传用户头像选择的图片path：" + pathTemp);
                        imgLocalList.clear();
                        imgLocalList.add(pathTemp);
                        scPhoto();
                    }
                    break;
            }
        }
    }
}